﻿/*
 * @author: wizardc
 */

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Dou.UI
{
    /// <summary>
    /// 绘制特定形状的图形，技能图
    /// </summary>
    public class UIPolygon : MaskableGraphic
    {
        private List<Vector2Int> _points = new List<Vector2Int>();
        private List<Color> _colors = new List<Color>();

        protected override void OnRectTransformDimensionsChange()
        {
            base.OnRectTransformDimensionsChange();
            SetVerticesDirty();
            SetMaterialDirty();
        }

        protected override void OnPopulateMesh(VertexHelper vh)
        {
            if (_points == null || _points.Count < 2)
            {
                base.OnPopulateMesh(vh);
                return;
            }
            vh.Clear();
            Vector2 center = new Vector2(0, 0);
            int count = _points.Count;
            for (int i = 0; i < count; i++)
            {
                AddTriangle(vh, _points[i], i == count - 1 ? _points[0] : _points[i + 1], center, _colors[i], i == count - 1 ? _colors[0] : _colors[i + 1], this.color, Vector2.zero, Vector2.one);
            }
        }

        private void AddTriangle(VertexHelper vh, Vector2 point1, Vector2 point2, Vector2 point3, Color c1, Color c2, Color c3, Vector2 uvCorner1, Vector2 uvCorner2)
        {
            int i = vh.currentVertCount;
            UIVertex vert = new UIVertex();
            vert.position = point1;
            vert.uv0 = uvCorner1;
            vert.color = c1;
            vh.AddVert(vert);
            vert.position = point2;
            vert.uv0 = new Vector2(uvCorner2.x, uvCorner1.y);
            vert.color = c2;
            vh.AddVert(vert);
            vert.position = point3;
            vert.uv0 = uvCorner2;
            vert.color = c3;
            vh.AddVert(vert);
            vh.AddTriangle(i + 0, i + 2, i + 1);
        }

        public void AddPoint(Vector2Int point)
        {
            AddPoint(point, Color.white);
        }

        public void AddPoint(Vector2Int point, Color color)
        {
            if (_points == null)
            {
                _points = new List<Vector2Int>();
            }
            if (_colors == null)
            {
                _colors = new List<Color>();
            }
            _points.Add(point);
            _colors.Add(color);
            SetVerticesDirty();
            SetMaterialDirty();
        }

        public void ClearPoints()
        {
            _points?.Clear();
            SetVerticesDirty();
            SetMaterialDirty();
        }
    }
}
